package com.bruce.cloud.feign.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;

/**
 * Created by bruce in 2025/6/27 15:27
 */
public class LogRetryListener implements RetryListener {

    private static final Logger log = LoggerFactory.getLogger(LogRetryListener.class);

    public static final String ACTION_NAME = "action-name";

    public LogRetryListener() {
    }

    @Override
    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        String actionName = (String) context.getAttribute(ACTION_NAME);
        if (actionName == null) {
            return;
        }
        Integer maxAttempts = (Integer) context.getAttribute("context.max-attempts");
        if (maxAttempts != null) {
            if (maxAttempts > context.getRetryCount()) {
                log.info("[{}] 执行异常,等待第[{}]次重试", actionName, context.getRetryCount());
                return;
            }
            if (maxAttempts == context.getRetryCount()) {
                log.info("[{}] 重试失败,重试总次数:{}", actionName, (context.getRetryCount() - 1));
            }
        }
    }

    @Override
    public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) {
        String actionName = (String) context.getAttribute(ACTION_NAME);
        if (actionName == null) {
            return;
        }
        if (context.getRetryCount() > 0) {
            log.info("[{}] 重试成功,重试总次数:{}", actionName, context.getRetryCount());
        }
    }


}
